<template>
    <el-dialog :title="title" :visible="dialogVisible" @close="cancelClick">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="姓名" prop="username">
                <el-input v-model="form.username" placeholder="请输入姓名" style="width: 80%;"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号" style="width: 80%;"></el-input>
            </el-form-item>
            <el-form-item label="入职日期" prop="timeOfEntry">
                <el-date-picker type="date" v-model="form.timeOfEntry" placeholder="请选择入职时间" style="width: 80%;" />
            </el-form-item>
            <el-form-item label="聘用形式" prop="formOfEmployment">
                <el-select v-model="form.formOfEmployment" placeholder="请选择聘用形式" style="width: 80%;">
                    <el-option :label="item.value" :value="item.id" v-for="item in hireTypeList" :key="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="工号" prop="workNumber">
                <el-input v-model="form.workNumber" placeholder="请输入工号" style="width: 80%;"></el-input>
            </el-form-item>
            <el-form-item label="部门" prop="departmentName">
                <!-- :show-all-levels="false" 显示选中项最后一级的标签，而不是选中项所在的完整路径。 -->
                <!-- visible-change 表示下拉框出现/隐藏时触发事件 -->
                <!-- props配置说明： 
                 label：指定选项标签为选项对象的某个属性值
                 value：指定选项的值为选项对象的某个属性值
                 emitPath：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
                -->
                <el-cascader @visible-change="getDepartments" v-model="form.departmentName" 
                    placeholder="请选择部门"
                    :options="departmentsList" 
                    :props="{label: 'name', value: 'name', emitPath: false}" 
                    :show-all-levels="false" 
                    style="width: 80%;"
                />
            </el-form-item>
            <el-form-item label="转正日期" prop="correctionTime">
                <el-date-picker type="date" v-model="form.correctionTime" placeholder="请选择转正时间" style="width: 80%;" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancelClick">取 消</el-button>
            <el-button type="primary" @click="confirmClick">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { addEmployee, getEmployeesList } from '@/api/employees'
import employeesEnum from '@/utils/enum/employees'
import { getDepartments } from '@/api/departments'
import { translateToTreeList } from '@/utils/index'

export default {
    name: 'AddEmployee',
    props: {
        // 弹层的标题
        title: {
            type: String,
            required: true
        },
        // 弹层的展示
        dialogVisible: {
            type: Boolean,
            required: true
        }
    },
    data() {
        // 校验工号是否重复
        const checkWorkNumber = async (rule, value, callback) => {
            const { rows } = await getEmployeesList({page: 1, size: 9999})
            let isRepeat = false
            if (this.title === '新增员工') {
                // 新增条件下的筛选
                isRepeat = rows.some(item => item.workNumber === value)
            } 
            // else {
            //     // 编辑条件下的筛选
            //     isRepeat = rows.some(item => item.workNumber === value && item.id !== this.employee.id)
            // }

            // isRepeat 为true，表明有重复
            if (isRepeat) {
                callback(new Error(`工号${value}已存在`))
            } else {
                callback()
            }
        }
        // 校验入职时间是否小于转正时间
        const checkTime = (rule, value, callback) => {
            if(this.form.timeOfEntry === '') {
                callback()
            } else {
                if(value < this.form.timeOfEntry) {
                    callback(new Error('转正时间不能小于入职时间'))
                } else {
                    callback()
                }
            }
        }
        return {
            form: {
                username: '',
                mobile: '',
                timeOfEntry: '',
                formOfEmployment: '',
                workNumber: '',
                departmentName: '',
                correctionTime: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 1, max: 10, message: '长度在1-10个字符', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
                ],
                timeOfEntry: [
                    { required: true, message: '请选择入职时间', trigger: 'blur' }
                ],
                formOfEmployment: [
                    { required: true, message: '请选择聘用形式', trigger: 'change' }
                ],
                workNumber: [
                    { required: true, message: '请输入工号', trigger: 'blur' },
                    { validator: checkWorkNumber, trigger: 'blur'}
                ],
                departmentName: [
                    { required: true, message: '请选择部门', trigger: 'change' }
                ],
                correctionTime: [
                    { required: true, message: '请选择转正时间', trigger: 'blur' },
                    { validator: checkTime, trigger: 'blur'}
                ],
            },
            hireTypeList: employeesEnum.hireType, // 聘用形式列表
            departmentsList: [] // 部门列表
        }
    },
    methods: {
        // 获取部门列表
        async getDepartments() {
            const { depts } = await getDepartments()
            // 将扁平化数据转为树形
            this.departmentsList = translateToTreeList(depts, '')
        },
        // 确定提交（新增或编辑操作）
        confirmClick() {
            this.$refs['form'].validate(async (valid) => {
                if (valid) {
                    // 校验通过
                    if (this.title === '新增员工') {
                        // 新增员工操作
                        await addEmployee(this.form)
                        this.$message.success('新增员工成功')
                    } 
                    // else {
                    //     // 编辑员工操作
                    //     await updDepartment(this.department.id, this.form)
                    //     this.$message.success('编辑员工成功')
                    // }
                    this.$emit('confirmClick')
                } else {
                    // 校验失败
                    console.log('校验未通过');
                    return false;
                }
            })
        },
        // 取消操作
        cancelClick() {
            // 因为我们有编辑操作，需要手动将this.form恢复为原始状态，光靠this.$refs['form'].resetFields()是不行的
            // this.$refs['form'].resetFields()并不是清空表单数据，而是对整个表单进行重置，将所有字段值重置为初始值，并移除校验结果

            // 假如没有手动将this.form恢复为原始状态，在编辑状态下，然后关闭弹层，去vue调试里看，
            // 会发现form数据并没有清空（仍为回显的内容，因为form初始值在父组件里this.$refs.addDept.form = department已经被赋值了，并不为空）
            this.form = {
                name: '',
                code: '',
                manager: '',
                introduce: ''
            }
            this.$refs['form'].resetFields()
            // 关闭弹层
            this.$emit('update:dialogVisible', false)
        }
    }
}
</script>

<style></style>